#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@desc: .

@Project ：kuberCloudTest 
@File ：disks.py
@Author ：admin
@Date ：2024/3/27 16:07 
"""
from kuberCloudTest.cloud_resources.volumes.urls import DiskUrls
from kuberCloudTest.cloud_resources.volumes.utils import DiskUtils
from kuberCloudTest.common.constant import OFFSET, LIMIT, AsyncType
from kuberCloudTest.common.utils import _getDetail, _getLogAction, _getOperationType
from kuberCloudTest.exception import KuberCloudException


def get_utils(accessToken):
    return DiskUtils(accessToken=accessToken)


def getDataMirror(accessToken, **kwargs):
    """
    获取云盘镜像列表
    :param accessToken:
    :param kwargs: limit:
                   offset:
                   keyword: xxx
    :return:
    """
    return get_utils(accessToken).cloud_http_request.get(DiskUrls.getDataMirror.value,
                                                         {
                                                             'offset': kwargs.get('offset', OFFSET),
                                                             'limit': kwargs.get('limit', LIMIT),
                                                             'keyword': kwargs.get('keyword', ''),
                                                             'servicetype': 1
                                                         })


def getDataDisk(accessToken, **kwargs):
    """
    获取数据云盘列表
    :param accessToken: access token
    :param kwargs: offset:
                   limit:
                   keyword: xxx
                   searchItem: 0: 云盘名称; 1: 云盘UUID; 2: 所有者名称; 3: 物理机IP; 4：主存储名称; 5：云主机名称
                   labelId: label uuid
    :return:
    """
    params = {'offset': kwargs.get('offset', OFFSET),
              'limit': kwargs.get('limit', LIMIT),
              'searchitem': kwargs.get('searchItem', 0),
              'keyword': kwargs.get('keyword', ''),
              'labelId': kwargs.get('labelId', '')}
    return get_utils(accessToken).cloud_http_request.get(DiskUrls.getDataDisk.value, params)


def getDataDiskById(accessToken, diskId):
    """
    根据ID获取数据盘
    :param accessToken: access token
    :param diskId: 数据盘UUID
    :return:
    """
    return get_utils(accessToken).cloud_http_request.get(DiskUrls.getDataDiskById.value, {'volumeid': diskId})


def getDataDiskDetail(accessToken, diskId):
    """
    根据uuid获取云盘详情
    :param accessToken: access token
    :param diskId: 数据盘UUID
    :return:
    """
    dataDisks = getDataDisk(accessToken)
    total = dataDisks.get('total', 0)
    content = getDataDisk(accessToken, limit=total, offset=OFFSET)
    return _getDetail(content, diskId, 'volumeid')


def createDataDiskBySpec(accessToken, name, specId, storageId, hostId,
                         preallocation: str = 'off',
                         isshareable: bool = False,
                         batchCreate: bool = False,
                         number: int = 1,
                         vmid='',
                         virtioscsi: bool = True,
                         remark=''):
    """
    通过规格创建云盘
    :param accessToken: access token
    :param name: 云盘名称
    :param specId: 规格ID
    :param storageId: 存储ID
    :param hostId: 物理机ID
    :param preallocation: 预分配策略off：精简置备;full：厚置备（延迟置零）;falloc：厚置备（置零）
    :param isshareable: 是否共享盘（共享云盘不能进行批量创建）
    :param batchCreate: 是否批量创建
    :param number: 批量创建数量范围,范围[1-99]
    :param vmid: 云主机ID，批量上传时无此字段
    :param virtioscsi: VirtioSCSI,默认true
    :param remark: 简介
    :return:
    """

    operationType = 1901
    data = _getLogAction(operationType, AsyncType.ASYNC.value)

    data['createtype'] = 0
    data['name'] = name
    data['vmid'] = vmid
    data['specid'] = specId
    data['msid'] = storageId
    data['hostid'] = hostId
    data['preallocation'] = preallocation
    data['isshareable'] = isshareable
    data['batchCreate'] = batchCreate
    data['number'] = number
    data['virtioscsi'] = virtioscsi
    data['remark'] = remark

    return get_utils(accessToken).cloud_http_request.post(DiskUrls.createDataDisk.value, data=data)


def createDataDiskByImage(accessToken, name, storageId, vmid, imageId,
                          preallocation: str = 'off',
                          virtioscsi: bool = True,
                          remark=''):
    """
    通过云盘镜像创建云盘
    :param accessToken: access token
    :param name: 云盘名称
    :param storageId: 存储ID
    :param imageId: 云盘镜像ID
    :param vmid: 云主机ID
    :param preallocation: 预分配策略off：精简置备;full：厚置备（延迟置零）;falloc：厚置备（置零）
    :param virtioscsi: VirtioSCSI,默认true
    :param remark: 简介
    :return:
    """
    operationType = 1901
    data = _getLogAction(operationType, AsyncType.ASYNC.value)
    data['createtype'] = 1
    data['name'] = name
    data['vmid'] = vmid
    data['msid'] = storageId
    data['rootimageid'] = imageId
    data['preallocation'] = preallocation
    data['isshareable'] = False
    data['virtioscsi'] = virtioscsi
    data['remark'] = remark

    return get_utils(accessToken).cloud_http_request.post(DiskUrls.createDataDisk.value, data=data)


def plugDisk(accessToken, diskId, vmid):
    """
    云主机挂载云盘
    :param accessToken: access token
    :param diskId: 云盘ID
    :param vmid: 云主机ID
    :return:
    """
    operationType = 1906
    data = _getLogAction(operationType, AsyncType.ASYNC.value)
    data['vmid'] = vmid
    data['volumeid'] = diskId

    return get_utils(accessToken).cloud_http_request.post(DiskUrls.plugDisk.value, data=data)


def unplugDisk(accessToken, diskId, vmid):
    """
    云主机卸载云盘
    :param accessToken: access token
    :param diskId: 云盘ID
    :param vmid: 云主机ID
    :return:
    """
    operationType = 1907
    data = _getLogAction(operationType, AsyncType.ASYNC.value)
    data['vmid'] = vmid
    data['volumeid'] = diskId

    return get_utils(accessToken).cloud_http_request.post(DiskUrls.unplugDisk.value, data=data)


def deleteDisk(accessToken, diskIds):
    """
    删除云主机
    :param accessToken: access token
    :param diskIds: 数据盘UUID(多个使用英文逗号分割)
    :return:
    """
    operationType = 1903
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['ids'] = diskIds
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.removeDataDisk.value, data=data)


def startDisk(accessToken, diskIds):
    """
    启用数据盘
    :param accessToken: access token
    :param diskIds: 数据盘UUID(多个使用英文逗号分割)
    :return:
    """
    operationType = 1904
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['ids'] = diskIds
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.startDataDisk.value, data=data)


def stopDisk(accessToken, diskIds):
    """
    停用数据盘
    :param accessToken: access token
    :param diskIds: 数据盘UUID(多个使用英文逗号分割)
    :return:
    """
    operationType = 1905
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['ids'] = diskIds
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.stopDataDisk.value, data=data)


def resizeDisk(accessToken, diskId, unit: str, size: int):
    """
    数据盘扩容
    :param accessToken: access token
    :param diskId: 数据盘UUID
    :param unit: 单位 GB|TB
    :param size: 容量
    :return:
    """
    operationType = 1912
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['volumeid'] = diskId
    data['sizeunit'] = unit
    data['size'] = size
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.resizeDataDisk.value, data=data)


def getDiskSnapshots(accessToken, diskId, **kwargs):
    """
    获取云盘快照列表
    :param accessToken: access token
    :param diskId: 数据盘UUID
    :param kwargs: limit:
                   offset:
                   keyword: xxx
    :return:
    """
    return get_utils(accessToken).cloud_http_request.get(DiskUrls.getDataDiskSnaps.value,
                                                         {
                                                             'offset': kwargs.get('offset', OFFSET),
                                                             'limit': kwargs.get('limit', LIMIT),
                                                             'volumeid': diskId
                                                         })


def createDiskSnapshot(accessToken, diskId, name, remark=''):
    """
    创建云盘快照
    :param accessToken: access token
    :param diskId: 数据盘UUID
    :param name: 快照名称
    :param remark: 快照简介
    :return:
    """
    operationType = 1917
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['volumeid'] = diskId
    data['name'] = name
    data['remark'] = remark
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.createDataDiskSnap.value, data=data)


def updateDiskSnapshot(accessToken, snapshotId, name, remark=''):
    """
    更新云盘快照
    :param accessToken: access token
    :param snapshotId: 快照ID
    :param name: 快照名称
    :param remark: 快照简介
    :return:
    """
    operationType = 1922
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['id'] = snapshotId
    data['name'] = name
    data['remark'] = remark
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.updateDataDiskSnap.value, data=data)


def rollbackDiskSnapshot(accessToken, snapshotId):
    """
    回滚云盘快照
    :param accessToken: access token
    :param snapshotId: 快照ID
    :return:
    """
    operationType = 1919
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['id'] = snapshotId
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.rollbackDataDiskSnap.value, data=data)


def deleteDiskSnapshot(accessToken, snapshotIds):
    """
    删除云盘快照
    :param accessToken: access token
    :param snapshotIds: 快照ID(多个使用英文逗号分割)
    :return:
    """
    operationType = 1918
    data = _getOperationType(operationType, AsyncType.ASYNC.value)
    data['ids'] = snapshotIds
    return get_utils(accessToken).cloud_http_request.post(DiskUrls.removeDataDiskSnap.value, data=data)
